/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package it.polimi.games.epkb.controller;

import it.polimi.games.epkb.controller.exceptions.NonexistentEntityException;
import it.polimi.games.epkb.controller.exceptions.PreexistingEntityException;
import it.polimi.games.epkb.entityClasses.ObservedComponent;
import it.polimi.games.epkb.entityClasses.ObservedComponentPK;
import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import it.polimi.games.epkb.entityClasses.SensorType;
import it.polimi.games.epkb.entityClasses.Component;
import javax.transaction.UserTransaction;

/**
 *
 * @author plebani
 */
public class ObservedComponentJpaController implements Serializable {

    public ObservedComponentJpaController(EntityManagerFactory emf) {
        this.utx = null;
        this.emf = emf;
    }

    public ObservedComponentJpaController(UserTransaction utx, EntityManagerFactory emf) {
        this.utx = utx;
        this.emf = emf;
    }
    private UserTransaction utx = null;
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(ObservedComponent observedComponent) throws PreexistingEntityException, Exception {
        if (observedComponent.getObservedComponentPK() == null) {
            observedComponent.setObservedComponentPK(new ObservedComponentPK());
        }
        observedComponent.getObservedComponentPK().setIdSensorType(observedComponent.getSensorType().getId());
        observedComponent.getObservedComponentPK().setIdComponent(observedComponent.getComponent().getId());
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            SensorType sensorType = observedComponent.getSensorType();
            if (sensorType != null) {
                sensorType = em.getReference(sensorType.getClass(), sensorType.getId());
                observedComponent.setSensorType(sensorType);
            }
            Component component = observedComponent.getComponent();
            if (component != null) {
                component = em.getReference(component.getClass(), component.getId());
                observedComponent.setComponent(component);
            }
            em.persist(observedComponent);
            if (sensorType != null) {
                sensorType.getObservedComponentCollection().add(observedComponent);
                sensorType = em.merge(sensorType);
            }
            if (component != null) {
                component.getObservedComponentCollection().add(observedComponent);
                component = em.merge(component);
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            if (findObservedComponent(observedComponent.getObservedComponentPK()) != null) {
                throw new PreexistingEntityException("ObservedComponent " + observedComponent + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(ObservedComponent observedComponent) throws NonexistentEntityException, Exception {
        observedComponent.getObservedComponentPK().setIdSensorType(observedComponent.getSensorType().getId());
        observedComponent.getObservedComponentPK().setIdComponent(observedComponent.getComponent().getId());
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            ObservedComponent persistentObservedComponent = em.find(ObservedComponent.class, observedComponent.getObservedComponentPK());
            SensorType sensorTypeOld = persistentObservedComponent.getSensorType();
            SensorType sensorTypeNew = observedComponent.getSensorType();
            Component componentOld = persistentObservedComponent.getComponent();
            Component componentNew = observedComponent.getComponent();
            if (sensorTypeNew != null) {
                sensorTypeNew = em.getReference(sensorTypeNew.getClass(), sensorTypeNew.getId());
                observedComponent.setSensorType(sensorTypeNew);
            }
            if (componentNew != null) {
                componentNew = em.getReference(componentNew.getClass(), componentNew.getId());
                observedComponent.setComponent(componentNew);
            }
            observedComponent = em.merge(observedComponent);
            if (sensorTypeOld != null && !sensorTypeOld.equals(sensorTypeNew)) {
                sensorTypeOld.getObservedComponentCollection().remove(observedComponent);
                sensorTypeOld = em.merge(sensorTypeOld);
            }
            if (sensorTypeNew != null && !sensorTypeNew.equals(sensorTypeOld)) {
                sensorTypeNew.getObservedComponentCollection().add(observedComponent);
                sensorTypeNew = em.merge(sensorTypeNew);
            }
            if (componentOld != null && !componentOld.equals(componentNew)) {
                componentOld.getObservedComponentCollection().remove(observedComponent);
                componentOld = em.merge(componentOld);
            }
            if (componentNew != null && !componentNew.equals(componentOld)) {
                componentNew.getObservedComponentCollection().add(observedComponent);
                componentNew = em.merge(componentNew);
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                ObservedComponentPK id = observedComponent.getObservedComponentPK();
                if (findObservedComponent(id) == null) {
                    throw new NonexistentEntityException("The observedComponent with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(ObservedComponentPK id) throws NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            ObservedComponent observedComponent;
            try {
                observedComponent = em.getReference(ObservedComponent.class, id);
                observedComponent.getObservedComponentPK();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The observedComponent with id " + id + " no longer exists.", enfe);
            }
            SensorType sensorType = observedComponent.getSensorType();
            if (sensorType != null) {
                sensorType.getObservedComponentCollection().remove(observedComponent);
                sensorType = em.merge(sensorType);
            }
            Component component = observedComponent.getComponent();
            if (component != null) {
                component.getObservedComponentCollection().remove(observedComponent);
                component = em.merge(component);
            }
            em.remove(observedComponent);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<ObservedComponent> findObservedComponentEntities() {
        return findObservedComponentEntities(true, -1, -1);
    }

    public List<ObservedComponent> findObservedComponentEntities(int maxResults, int firstResult) {
        return findObservedComponentEntities(false, maxResults, firstResult);
    }

    private List<ObservedComponent> findObservedComponentEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(ObservedComponent.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public ObservedComponent findObservedComponent(ObservedComponentPK id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(ObservedComponent.class, id);
        } finally {
            em.close();
        }
    }

    public int getObservedComponentCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<ObservedComponent> rt = cq.from(ObservedComponent.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
